<template>
  <div class="admin-user-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-row">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <el-icon :size="40" color="#409eff"><User /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.totalCount || 0 }}</div>
              <div class="stat-label">管理员总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <el-icon :size="40" color="#67c23a"><CircleCheck /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.activeCount || 0 }}</div>
              <div class="stat-label">活跃用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <el-icon :size="40" color="#e6a23c"><UserFilled /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.adminCount || 0 }}</div>
              <div class="stat-label">超级管理员</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <el-icon :size="40" color="#f56c6c"><WarningFilled /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.bannedCount || 0 }}</div>
              <div class="stat-label">已禁用</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索用户名/手机号/邮箱"
            clearable
            style="width: 240px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部状态" clearable style="width: 120px">
            <el-option label="活跃" value="active" />
            <el-option label="已禁用" value="banned" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><RefreshLeft /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleCreate" v-permission-role="'SUPER_ADMIN'">
            <el-icon><Plus /></el-icon>
            新建管理员
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <el-table
        :data="userList"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="用户信息" width="220">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :src="row.avatar" :size="40">{{ row.nickname?.charAt(0) }}</el-avatar>
              <div class="user-detail">
                <div class="nickname">{{ row.nickname }}</div>
                <div class="contact">{{ row.phone || row.email || '-' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="角色" width="200">
          <template #default="{ row }">
            <el-tag
              v-for="roleName in row.roleNames"
              :key="roleName"
              size="small"
              style="margin-right: 5px"
            >
              {{ roleName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'" size="small">
              {{ row.status === 'active' ? '活跃' : '已禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginAt" label="最后登录" width="180">
          <template #default="{ row }">
            {{ row.lastLoginAt ? formatDate(row.lastLoginAt) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="280">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleEdit(row)"
              v-permission-role="'SUPER_ADMIN'"
            >
              编辑
            </el-button>
            <el-button
              :type="row.status === 'active' ? 'warning' : 'success'"
              size="small"
              link
              @click="handleToggleStatus(row)"
              v-permission-role="'SUPER_ADMIN'"
            >
              {{ row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="info"
              size="small"
              link
              @click="handleResetPassword(row)"
              v-permission-role="'SUPER_ADMIN'"
            >
              重置密码
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(row)"
              v-permission-role="'SUPER_ADMIN'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" :prop="isEdit ? '' : 'password'">
          <el-input
            v-model="formData.password"
            type="password"
            :placeholder="isEdit ? '留空则不修改' : '请输入密码'"
            show-password
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select 
            v-model="formData.roleIds" 
            multiple 
            placeholder="请选择角色" 
            style="width: 100%"
            collapse-tags
            collapse-tags-tooltip
          >
            <el-option
              v-for="role in availableRoles"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
          <div v-if="!isSuperAdmin" style="margin-top: 8px; color: #909399; font-size: 12px;">
            <el-icon style="vertical-align: middle;"><InfoFilled /></el-icon>
            您只能创建管理员、俱乐部管理员和场地管理员
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="active">活跃</el-radio>
            <el-radio label="banned">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import { adminUserApi } from '@/api/adminUser'
import { roleApi } from '@/api/role'
import { useUserStore } from '@/store/user'
import dayjs from 'dayjs'

// Store
const userStore = useUserStore()

// 数据
const loading = ref(false)
const userList = ref([])
const statistics = ref({})
const roleList = ref([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = computed(() => isEdit.value ? '编辑管理员' : '新建管理员')
const isEdit = ref(false)
const submitting = ref(false)

// 当前用户是否是超级管理员
const isSuperAdmin = computed(() => {
  const roles = userStore.userInfo?.roles || []
  return roles.includes('SUPER_ADMIN')
})

// 根据当前用户角色过滤可选角色
const availableRoles = computed(() => {
  const currentUserRoles = userStore.userInfo?.roles || []
  
  // 超级管理员可以选择所有角色
  if (currentUserRoles.includes('SUPER_ADMIN')) {
    return roleList.value
  }
  
  // 管理员只能选择特定角色
  if (currentUserRoles.includes('ADMIN')) {
    return roleList.value.filter(role => 
      ['ADMIN', 'CLUB_MANAGER', 'VENUE_MANAGER'].includes(role.code)
    )
  }
  
  // 其他角色不能创建用户（理论上不会到这里，因为按钮已被隐藏）
  return []
})

// 表单
const formRef = ref(null)
const formData = reactive({
  id: null,
  nickname: '',
  password: '',
  phone: '',
  email: '',
  roleIds: [],
  status: 'active'
})

const formRules = {
  nickname: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 4, message: '密码至少4位', trigger: 'blur' }
  ],
  roleIds: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 方法
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
}

const loadStatistics = async () => {
  try {
    const res = await adminUserApi.getAdminUserStatistics()
    statistics.value = res || {}
  } catch (error) {
    console.error('加载统计数据失败:', error)
    statistics.value = {}
  }
}

const loadRoles = async () => {
  try {
    const res = await roleApi.getAllRoles()
    roleList.value = res || []
  } catch (error) {
    console.error('加载角色列表失败:', error)
    roleList.value = []
  }
}

const loadData = async () => {
  loading.value = true
  try {
    const res = await adminUserApi.getAdminUserList({
      page: pagination.page,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      status: searchForm.status
    })
    userList.value = res.records || []
    pagination.total = res.total || 0
  } catch (error) {
    ElMessage.error('加载数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  searchForm.keyword = ''
  searchForm.status = ''
  handleSearch()
}

const handleCreate = () => {
  isEdit.value = false
  dialogVisible.value = true
  Object.assign(formData, {
    id: null,
    nickname: '',
    password: '',
    phone: '',
    email: '',
    roleIds: [],
    status: 'active'
  })
}

const handleEdit = (row) => {
  isEdit.value = true
  dialogVisible.value = true
  Object.assign(formData, {
    id: row.id,
    nickname: row.nickname,
    password: '',
    phone: row.phone || '',
    email: row.email || '',
    roleIds: row.roles.map(r => r.id),
    status: row.status
  })
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      await adminUserApi.updateAdminUser(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      await adminUserApi.createAdminUser(formData)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadData()
    loadStatistics()
  } catch (error) {
    if (error !== false) {
      ElMessage.error(error.message || '操作失败')
    }
  } finally {
    submitting.value = false
  }
}

const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status === 'active' ? 'banned' : 'active'
    await ElMessageBox.confirm(
      `确定要${newStatus === 'active' ? '启用' : '禁用'}该用户吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await adminUserApi.updateAdminUserStatus(row.id, newStatus)
    ElMessage.success('操作成功')
    loadData()
    loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleResetPassword = async (row) => {
  try {
    const { value: newPassword } = await ElMessageBox.prompt(
      '请输入新密码',
      '重置密码',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.{4,}/,
        inputErrorMessage: '密码至少4位'
      }
    )
    
    await adminUserApi.resetAdminUserPassword(row.id, newPassword)
    ElMessage.success('密码重置成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${row.nickname} 吗？此操作不可恢复！`,
      '警告',
      { type: 'warning', confirmButtonText: '确定删除', cancelButtonText: '取消' }
    )
    
    await adminUserApi.deleteAdminUser(row.id)
    ElMessage.success('删除成功')
    loadData()
    loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handlePageChange = (page) => {
  pagination.page = page
  loadData()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 生命周期
onMounted(() => {
  loadData()
  loadStatistics()
  loadRoles()
})
</script>

<style scoped lang="scss">
.admin-user-container {
  padding: 20px;
}

.statistics-row {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 15px;

  .stat-info {
    .stat-value {
      font-size: 28px;
      font-weight: bold;
      color: #303133;
    }

    .stat-label {
      font-size: 14px;
      color: #909399;
      margin-top: 5px;
    }
  }
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  .user-info {
    display: flex;
    align-items: center;
    gap: 10px;

    .user-detail {
      .nickname {
        font-weight: 500;
        color: #303133;
      }

      .contact {
        font-size: 12px;
        color: #909399;
        margin-top: 4px;
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

